#!/bin/bash

# 设置部署目录和项目名称
DIR="/data/app"
app_id="springboot-jenkins-test"
echo "$app_id project start deployment..."

# 设置待部署的应用服务器（可以部署多台应用服务器，各IP地址使用空格隔开）
servers_ip=(114.215.139.240)
for server_ip in ${servers_ip[@]}
do

echo "$server_ip : $app_id project start deployment..."
# SSH连接应用服务器进行备份操作
echo "$server_ip : $app_id project start backup..."
ssh -Tq -oStrictHostKeyChecking=no root@${server_ip} <<EOF
mkdir -p ${DIR}/backup/${app_id}
mkdir -p ${DIR}/${app_id}
if [ -f "${DIR}/${app_id}/${app_id}.jar" ];then
  mv ${DIR}/${app_id}/${app_id}.jar ${DIR}/backup/${app_id}/${app_id}-`date "+%Y%m%d_%H%M%S"`.jar
fi
EOF

# 拷贝构建jar包及相关脚本到应用服务器的部署目录中
echo "$server_ip : $app_id project start copy..."
scp -q -oStrictHostKeyChecking=no ${WORKSPACE}/target/*.jar root@${server_ip}:${DIR}/${app_id}/${app_id}.jar
echo "$server_ip : $app_id project's shell script start copy..."
scp -q -oStrictHostKeyChecking=no ${WORKSPACE}/src/main/resources/deploy/start.sh root@${server_ip}:${DIR}/${app_id}/start.sh
scp -q -oStrictHostKeyChecking=no ${WORKSPACE}/src/main/resources/deploy/stop.sh root@${server_ip}:${DIR}/${app_id}/stop.sh

# SSH连接应用实现项目的发布
echo "$server_ip : $app_id project start launch..."
ssh -q -oStrictHostKeyChecking=no root@${server_ip} <<EOF
cd ${DIR}/${app_id}/
chmod +x ./start.sh
chmod +x ./stop.sh
sh ./stop.sh
sh ./start.sh
EOF

done

echo "$app_id project has been successfully deployed..."